package me.zhengjie.modules.system.service.zf.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.system.converter.MachineConverter;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.domain.entity.BrandProductsLine;
import me.zhengjie.modules.system.domain.entity.ProductsLine;
import me.zhengjie.modules.system.domain.entity.SysUserMerchant;
import me.zhengjie.modules.system.domain.req.SysUserMerchantReqDTO;
import me.zhengjie.modules.system.domain.req.zf.*;
import me.zhengjie.modules.system.domain.rsp.BankRspDTO;
import me.zhengjie.modules.system.domain.rsp.CityRspDTO;
import me.zhengjie.modules.system.domain.rsp.zf.*;
import me.zhengjie.modules.system.enums.ChannelEnum;
import me.zhengjie.modules.system.enums.TokenTypeToPathEnum;
import me.zhengjie.modules.system.service.BrandProductsLineService;
import me.zhengjie.modules.system.service.ProductsLineService;
import me.zhengjie.modules.system.service.SysUserMerchantService;
import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.modules.system.service.zf.MerchantMachineService;
import me.zhengjie.modules.system.utils.common.NoUtil;
import me.zhengjie.modules.system.utils.common.PhotoUtil;
import me.zhengjie.modules.system.utils.zf.DESUtil;
import me.zhengjie.utils.SecurityUtils;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@RequiredArgsConstructor
@Slf4j
public class MerchantMachineServiceImpl implements MerchantMachineService {

    static String CODE = ChannelEnum.ZF.getCode();
    private final SysUserMerchantService sysUserMerchantService;
    private final BrandProductsLineService brandProductsLineService;
    private final ProductsLineService productsLineService;
    private final UserService userService;

    @Override
    public Boolean smallMerchantNetworkAccess(SmallMerchantNetworkAccessReqDTO reqDTO) {
        BrandProductsLine brandProductsLine = queryBrandProductsLineByUser(SecurityUtils.getCurrentUserId(), CODE);
        TokenTypeToPathEnum pathEnum = TokenTypeToPathEnum.findOne(TokenTypeToPathEnum.SMALL_MERCHANT_ACCESS_PATH.getTokenType());
        String agentId = brandProductsLine.getAgentId();
        String token = getToken(agentId, brandProductsLine.getAesKey(), pathEnum.getTokenType());
        try {
            SortedMap<String, Object> parameters = new TreeMap<>();
            parameters.put("agentId", agentId);
            parameters.put("token", token);
            parameters.put("reqFlowNo", NoUtil.getOrderNo(32));
            parameters.put("contactsMobile", DESUtil.encrypt(reqDTO.getAccountMobile()));
            parameters.put("idCard", DESUtil.encrypt(reqDTO.getIdCard()));
            parameters.put("idCardDateStart", reqDTO.getIdCardDateStart());
            parameters.put("idCardDateEnd", reqDTO.getIdCardDateEnd());
            parameters.put("provinceName", reqDTO.getProvinceName());
            parameters.put("provinceCode", reqDTO.getProvinceCode());
            parameters.put("cityName", reqDTO.getCityName());
            parameters.put("cityCode", reqDTO.getCityCode());
            parameters.put("countyName", reqDTO.getCountyName());
            parameters.put("countyCode", reqDTO.getCityCode());
            parameters.put("busiAddr", reqDTO.getBusiAddr());
            parameters.put("cFeeRate", reqDTO.getCFeeRate());
            parameters.put("dFeeRate", reqDTO.getDFeeRate());
            parameters.put("dFeeMax", reqDTO.getDFeeMax());
            parameters.put("wechatPayFeeRate", reqDTO.getWechatPayFeeRate());
            parameters.put("alipayFeeRate", reqDTO.getAlipayFeeRate());
            parameters.put("ycFreeFeeRate", reqDTO.getYcFreeFeeRate());
            parameters.put("ydFreeFeeRate", reqDTO.getYdFreeFeeRate());
            parameters.put("d0FeeRate", reqDTO.getDlFeeRate());
            parameters.put("d0SingleCashDrawal", reqDTO.getDlSingleCashDrawal());
            parameters.put("accountType", "S");
            parameters.put("accountId", DESUtil.encrypt(reqDTO.getAccountId()));
            parameters.put("accountName", reqDTO.getAccountName());
            parameters.put("accountMobile", reqDTO.getAccountMobile());
            parameters.put("accountIdCard", reqDTO.getAccountIdCard());
            parameters.put("bankCode", reqDTO.getBankCode());
            parameters.put("bankName", reqDTO.getBankName());
            parameters.put("termSn", token);
            //组装imgList
            HashMap<String, Object> idCardFront = new HashMap<>();
            idCardFront.put("img", PhotoUtil.transFerLinkToBase64(reqDTO.getIdCardFrontPhoto()));
            idCardFront.put("imgSuffix", "jpg");
            idCardFront.put("imgType", "2");
            HashMap<String, Object> idCardBack = new HashMap<>();
            idCardBack.put("img", PhotoUtil.transFerLinkToBase64(reqDTO.getIdCardBackPhoto()));
            idCardBack.put("imgSuffix", "jpg");
            idCardBack.put("imgType", "3");
            HashMap<String, Object> bankCard = new HashMap<>();
            bankCard.put("img", PhotoUtil.transFerLinkToBase64(reqDTO.getBankCardPhoto()));
            bankCard.put("imgSuffix", "jpg");
            bankCard.put("imgType", "4");
            parameters.put("imgList", CollUtil.newArrayList(idCardFront, idCardBack, bankCard));
            CommonResult commonResult = sendPost(getPath(pathEnum.getPath()), parameters, brandProductsLine.getAesKey());
            log.info("smallMerchantNetworkAccess={}", JSONUtil.toJsonStr(commonResult));
            NetworkAccessRspDTO networkAccessRspDTO = JSONUtil.toBean(commonResult.getData(), NetworkAccessRspDTO.class);
            //保存商户
            SysUserMerchant sysUserMerchant = SysUserMerchant.builder()
                    .userId(SecurityUtils.getCurrentUserId())
                    .merchantId(networkAccessRspDTO.getMerchId())
                    .merchantName(networkAccessRspDTO.getMerchName())
                    .agentId(networkAccessRspDTO.getAgentId())
                    .reqFlowNo(networkAccessRspDTO.getReqFlowNo())
                    .productLineId(brandProductsLine.getProductLineId())
                    .build();
            SysUserMerchantReqDTO sysUserMerchantReqDTO = MachineConverter.INSTANCE.sysUserMerchantDTOToReq(sysUserMerchant);
            sysUserMerchantService.save(sysUserMerchantReqDTO);
        } catch (Exception e) {
            throw new BadRequestException(Convert.toStr(e.getMessage(), "小微商户入网异常"));
        }
        return Boolean.TRUE;
    }

    @Override
    public Boolean merchantTerminalBinding(MerchantTerminalBindReqDTO reqDTO) {
        BrandProductsLine brandProductsLine = queryBrandProductsLineByUser(SecurityUtils.getCurrentUserId(), CODE);
        TokenTypeToPathEnum pathEnum = TokenTypeToPathEnum.findOne(TokenTypeToPathEnum.MERCHANT_TERMINAL_BIND_PATH.getTokenType());
        String agentId = brandProductsLine.getAgentId();
        String aesKey = brandProductsLine.getAesKey();
        String termSn = reqDTO.getTermSn();
        String token = getToken(agentId, aesKey, pathEnum.getTokenType());
        SortedMap<String, Object> parameters = new TreeMap<>();
        parameters.put("agentId", agentId);
        parameters.put("termSn", termSn);
        parameters.put("merchId", reqDTO.getMerchId());
        parameters.put("token", token);
        CommonResult commonResult = sendPost(getPath(TokenTypeToPathEnum.findOne(pathEnum.getTokenType()).getPath()), parameters, aesKey);
        log.info("merchantTerminalBinding={}", JSONUtil.toJsonStr(commonResult));
        return Boolean.TRUE;
    }

    @Override
    public Boolean merchantTerminalUnBinding(MerchantTerminalUnBindingReqDTO reqDTO) {
        BrandProductsLine brandProductsLine = queryBrandProductsLineByUser(SecurityUtils.getCurrentUserId(), CODE);
        TokenTypeToPathEnum pathEnum = TokenTypeToPathEnum.findOne(TokenTypeToPathEnum.MERCHANT_TERMINAL_UN_BIND_PATH.getTokenType());
        String agentId = brandProductsLine.getAgentId();
        String aesKey = brandProductsLine.getAesKey();
        String token = getToken(agentId, aesKey, pathEnum.getTokenType());
        SortedMap<String, Object> parameters = new TreeMap<>();
        parameters.put("agentId", agentId);
        parameters.put("termSn", reqDTO.getTermSn());
        parameters.put("merchId", reqDTO.getMerchId());
        parameters.put("token", token);
        CommonResult commonResult = sendPost(getPath(TokenTypeToPathEnum.findOne(pathEnum.getTokenType()).getPath()), parameters, aesKey);
        log.info("merchantTerminalUnBinding={}", JSONUtil.toJsonStr(commonResult));
        return Boolean.TRUE;
    }

    @Override
    public List<QueryMerchantTerminalRspDTO> queryMerchantTerminal(QueryMerchantTerminalReqDTO reqDTO) {
        BrandProductsLine brandProductsLine = queryBrandProductsLineByUser(SecurityUtils.getCurrentUserId(), CODE);
        TokenTypeToPathEnum pathEnum = TokenTypeToPathEnum.findOne(TokenTypeToPathEnum.QUERY_MERCHANT_TERMINAL_PATH.getTokenType());
        String agentId = brandProductsLine.getAgentId();
        String aesKey = brandProductsLine.getAesKey();
        String token = getToken(agentId, aesKey, pathEnum.getTokenType());
        SortedMap<String, Object> parameters = new TreeMap<>();
        parameters.put("agentId", agentId);
        parameters.put("merchId", reqDTO.getMerchId());
        parameters.put("token", token);
        CommonResult commonResult = sendPost(getPath(TokenTypeToPathEnum.findOne(pathEnum.getTokenType()).getPath()), parameters, aesKey);
        log.info("queryMerchantTerminal={}", JSONUtil.toJsonStr(commonResult));
        return JSONUtil.toList(commonResult.getData(), QueryMerchantTerminalRspDTO.class);
    }

    @Override
    public QueryMerchantBaseInfoRspDTO queryMerchantBaseInfo(QueryMerchantBaseInfoReqDTO reqDTO) {
        BrandProductsLine brandProductsLine = queryBrandProductsLineByUser(SecurityUtils.getCurrentUserId(), CODE);
        TokenTypeToPathEnum pathEnum = TokenTypeToPathEnum.findOne(TokenTypeToPathEnum.QUERY_MERCHANT_BASE_INFO_PATH.getTokenType());
        String agentId = brandProductsLine.getAgentId();
        String aesKey = brandProductsLine.getAesKey();
        String token = getToken(agentId, aesKey, pathEnum.getTokenType());
        SortedMap<String, Object> parameters = new TreeMap<>();
        parameters.put("agentId", agentId);
        parameters.put("merchId", reqDTO.getMerchId());
        parameters.put("token", token);
        CommonResult commonResult = sendPost(getPath(TokenTypeToPathEnum.findOne(pathEnum.getTokenType()).getPath()), parameters, aesKey);
        log.info("queryMerchantBaseInfo={}", JSONUtil.toJsonStr(commonResult));
        return JSONUtil.toBean(commonResult.getData(), QueryMerchantBaseInfoRspDTO.class);
    }

    @Override
    public QueryMerchantRateInfoRspDTO queryMerchantRateInfo(QueryMerchantRateInfoReqDTO reqDTO) {
        BrandProductsLine brandProductsLine = queryBrandProductsLineByUser(SecurityUtils.getCurrentUserId(), CODE);
        TokenTypeToPathEnum pathEnum = TokenTypeToPathEnum.findOne(TokenTypeToPathEnum.QUERY_MERCHANT_TATE_INFO_PATH.getTokenType());
        String agentId = brandProductsLine.getAgentId();
        String aesKey = brandProductsLine.getAesKey();
        String token = getToken(agentId, aesKey, pathEnum.getTokenType());
        SortedMap<String, Object> parameters = new TreeMap<>();
        parameters.put("agentId", agentId);
        parameters.put("merchId", reqDTO.getMerchId());
        parameters.put("token", token);
        CommonResult commonResult = sendPost(getPath(TokenTypeToPathEnum.findOne(pathEnum.getTokenType()).getPath()), parameters, aesKey);
        log.info("queryMerchantRateInfo={}", JSONUtil.toJsonStr(commonResult));
        return JSONUtil.toBean(commonResult.getData(), QueryMerchantRateInfoRspDTO.class);
    }

    @Override
    public QueryMerchantSettlementInfoRspDTO queryMerchantSettlementInfo(QueryMerchantSettlementInfoReqDTO reqDTO) {
        BrandProductsLine brandProductsLine = queryBrandProductsLineByUser(SecurityUtils.getCurrentUserId(), CODE);
        TokenTypeToPathEnum pathEnum = TokenTypeToPathEnum.findOne(TokenTypeToPathEnum.QUERY_MERCHANT_SETTLEMENT_INFO_PATH.getTokenType());
        String agentId = brandProductsLine.getAgentId();
        String aesKey = brandProductsLine.getAesKey();
        String merchId = reqDTO.getMerchId();
        String token = getToken(agentId, aesKey, pathEnum.getTokenType());
        SortedMap<String, Object> parameters = new TreeMap<>();
        parameters.put("agentId", agentId);
        parameters.put("merchId", merchId);
        parameters.put("token", token);
        CommonResult commonResult = sendPost(getPath(TokenTypeToPathEnum.findOne(pathEnum.getTokenType()).getPath()), parameters, aesKey);
        log.info("queryMerchantSettlementInfo={}", JSONUtil.toJsonStr(commonResult));
        return JSONUtil.toBean(commonResult.getData(), QueryMerchantSettlementInfoRspDTO.class);
    }

    @Override
    public Boolean smallMerchantBaseInfoUpdate(SmallMerchantBaseInfoUpdateReqDTO reqDTO) {
        BrandProductsLine brandProductsLine = queryBrandProductsLineByUser(SecurityUtils.getCurrentUserId(), CODE);
        TokenTypeToPathEnum pathEnum = TokenTypeToPathEnum.findOne(TokenTypeToPathEnum.SMALL_MERCHANT_BASE_INFO_UPDATE_PATH.getTokenType());
        String agentId = brandProductsLine.getAgentId();
        String aesKey = brandProductsLine.getAesKey();
        String token = getToken(agentId, aesKey, pathEnum.getTokenType());
        try {
            SortedMap<String, Object> parameters = new TreeMap<>();
            parameters.put("agentId", agentId);
            parameters.put("token", token);
            parameters.put("merchId", reqDTO.getMerchId());
            parameters.put("contactsName", reqDTO.getContactsName());
            parameters.put("contactsMobile", DESUtil.encrypt(reqDTO.getContactsMobile()));
            parameters.put("idCard", DESUtil.encrypt(reqDTO.getIdCard()));
            parameters.put("idCardDateStart", reqDTO.getIdCardDateStart());
            parameters.put("idCardDateEnd", reqDTO.getIdCardDeteEnd());
            parameters.put("provinceName", reqDTO.getProvinceName());
            parameters.put("provinceCode", reqDTO.getProvinceCode());
            parameters.put("cityName", reqDTO.getCityName());
            parameters.put("cityCode", reqDTO.getCityCode());
            parameters.put("countyName", reqDTO.getCountyName());
            parameters.put("countyCode", reqDTO.getCountyCode());
            parameters.put("busiAddr", reqDTO.getBusiAddr());
            //组装imgList
            HashMap<String, Object> idCardFront = new HashMap<>();
            idCardFront.put("img", PhotoUtil.transFerLinkToBase64(reqDTO.getIdCardFront()));
            idCardFront.put("imgSuffix", "jpg");
            idCardFront.put("imgType", "2");
            HashMap<String, Object> idCardBack = new HashMap<>();
            idCardBack.put("img", PhotoUtil.transFerLinkToBase64(reqDTO.getIdCardBack()));
            idCardBack.put("imgSuffix", "jpg");
            idCardBack.put("imgType", "3");
            parameters.put("imgList", CollUtil.newArrayList(idCardFront, idCardBack));
            CommonResult commonResult = sendPost(getPath(pathEnum.getPath()), parameters, aesKey);
            log.info("smallMerchantBaseInfoUpdate={}", JSONUtil.toJsonStr(commonResult));
        } catch (Exception e) {
            throw new BadRequestException(Convert.toStr(e.getMessage(), "小微商户基本信息修改失败"));
        }
        return Boolean.TRUE;
    }

    @Override
    public Boolean smallMerchantRateInfoUpdate(SmallMerchantRateInfoUpdateReqDTO reqDTO) {
        BrandProductsLine brandProductsLine = queryBrandProductsLineByUser(SecurityUtils.getCurrentUserId(), CODE);
        TokenTypeToPathEnum pathEnum = TokenTypeToPathEnum.findOne(TokenTypeToPathEnum.SMALL_MERCHANT_RATE_INFO_UPDATE_PATH.getTokenType());
        String agentId = brandProductsLine.getAgentId();
        String aesKey = brandProductsLine.getAesKey();
        String token = getToken(agentId, aesKey, pathEnum.getTokenType());
        try {
            SortedMap<String, Object> parameters = new TreeMap<>();
            parameters.put("agentId", agentId);
            parameters.put("token", token);
            parameters.put("merchId", reqDTO.getMerchId());
            parameters.put("cFeeRate", reqDTO.getCFeeRate());
            parameters.put("dFeeRate", reqDTO.getDFeeRate());
            parameters.put("dFeeMax", reqDTO.getDFeeMax());
            parameters.put("wechatPayFeeRate", reqDTO.getWechatPayFeeRate());
            parameters.put("alipayFeeRate", reqDTO.getAlipayFeeRate());
            parameters.put("ycFreeFeeRate", reqDTO.getYcFreeFeeRate());
            parameters.put("ydFreeFeeRate", reqDTO.getYdFreeFeeRate());
            parameters.put("d0FeeRate", reqDTO.getD0FeeRate());
            parameters.put("d0SingleCashDrawal", reqDTO.getD0SingleCashDrawal());
            CommonResult commonResult = sendPost(getPath(pathEnum.getPath()), parameters, aesKey);
            log.info("smallMerchantRateInfoUpdate={}", JSONUtil.toJsonStr(commonResult));
        } catch (Exception e) {
            throw new BadRequestException(Convert.toStr(e.getMessage(), "小微商户费率信息修改失败"));
        }
        return Boolean.TRUE;
    }

    @Override
    public Boolean smallMerchantSettlementInfoUpdate(SmallMerchantSettlementInfoUpdateReqDTO reqDTO) {
        BrandProductsLine brandProductsLine = queryBrandProductsLineByUser(SecurityUtils.getCurrentUserId(), CODE);
        TokenTypeToPathEnum pathEnum = TokenTypeToPathEnum.findOne(TokenTypeToPathEnum.SMALL_MERCHANT_SETTLEMENT_INFO_UPDATE_PATH.getTokenType());
        String agentId = brandProductsLine.getAgentId();
        String aesKey = brandProductsLine.getAesKey();
        String token = getToken(agentId, aesKey, pathEnum.getTokenType());
        try {
            SortedMap<String, Object> parameters = new TreeMap<>();
            parameters.put("agentId", agentId);
            parameters.put("token", token);
            parameters.put("merchId", reqDTO.getMerchId());
            parameters.put("accountId", DESUtil.encrypt(reqDTO.getAccountId()));
            parameters.put("accountMobile", DESUtil.encrypt(reqDTO.getAccountMobile()));
            parameters.put("bankCode", reqDTO.getBankCode());
            parameters.put("bankName", reqDTO.getBankName());
            HashMap<String, Object> bankCard = new HashMap<>();
            bankCard.put("img", PhotoUtil.transFerLinkToBase64(reqDTO.getBankCard()));
            bankCard.put("imgSuffix", "jpg");
            bankCard.put("imgType", "3");
            parameters.put("imgList", CollUtil.newArrayList(bankCard));
            CommonResult commonResult = sendPost(getPath(pathEnum.getPath()), parameters, aesKey);
            log.info("smallMerchantSettlementInfoUpdate={}", JSONUtil.toJsonStr(commonResult));
        } catch (Exception e) {
            throw new BadRequestException(Convert.toStr(e.getMessage(), "小微商户结算信息修改失败"));
        }
        return Boolean.TRUE;
    }

    @Override
    public Boolean businessMerchantBaseInfoUpdate(BusinessMerchantBaseInfoUpdateReqDTO reqDTO) {
        BrandProductsLine brandProductsLine = queryBrandProductsLineByUser(SecurityUtils.getCurrentUserId(), CODE);
        TokenTypeToPathEnum pathEnum = TokenTypeToPathEnum.findOne(TokenTypeToPathEnum.BUSINESS_MERCHANT_BASE_INFO_UPDATE_PATH.getTokenType());
        String agentId = brandProductsLine.getAgentId();
        String aesKey = brandProductsLine.getAesKey();
        String token = getToken(agentId, aesKey, pathEnum.getTokenType());
        try {
            SortedMap<String, Object> parameters = new TreeMap<>();
            parameters.put("agentId", agentId);
            parameters.put("token", token);
            parameters.put("merchId", reqDTO.getMerchId());
            parameters.put("gradeMerchLevel", reqDTO.getGradeMerchLevel());
            parameters.put("merchPname", reqDTO.getMerchPname());
            parameters.put("licenseType", reqDTO.getLicenseType());
            parameters.put("licenseNo", reqDTO.getLicenseNo());
            parameters.put("licenseAuth", reqDTO.getLicenseType());
            parameters.put("licenseStartTime", reqDTO.getLicenseStartTime());
            parameters.put("licenseEndTime", reqDTO.getLicenseEndTime());
            parameters.put("licenseAddr", reqDTO.getLicenseAddr());
            parameters.put("busiScope", reqDTO.getBusiScope());
            parameters.put("merchAddr", reqDTO.getMerchAddr());
            parameters.put("provinceName", reqDTO.getProvinceName());
            parameters.put("provinceCode", reqDTO.getProvinceCode());
            parameters.put("cityName", reqDTO.getCityName());
            parameters.put("cityCode", reqDTO.getCityCode());
            parameters.put("countyName", reqDTO.getCountyName());
            parameters.put("countyCode", reqDTO.getCountyCode());
            parameters.put("legalMobile", reqDTO.getLegalMobile());
            parameters.put("legalCertNo", reqDTO.getLegalCertNo());
            parameters.put("legalName", reqDTO.getLegalName());
            parameters.put("legalNation", reqDTO.getLegalNation());
            parameters.put("legalGender", reqDTO.getLegalGender());
            parameters.put("legalCertIssued", reqDTO.getLegalCertIssued());
            parameters.put("legalCertAddr", reqDTO.getLegalCertAddr());
            parameters.put("legalCertnoStartTime", reqDTO.getLegalCertnoStartTime());
            parameters.put("legalCertnoEndTime", reqDTO.getLegalCertnoEndTime());
            parameters.put("contacts", reqDTO.getContacts());
            parameters.put("contactsMobile", reqDTO.getContactsMobile());
            parameters.put("contactsCertNo", reqDTO.getContactsCertNo());
            parameters.put("certStartDate", reqDTO.getCertStartDate());
            parameters.put("certEndDate", reqDTO.getCertEndDate());
            parameters.put("contactsNation", reqDTO.getContactsNation());
            parameters.put("contactsGender", reqDTO.getContactsGender());
            parameters.put("contactsCertAddr", reqDTO.getContactsCertAddr());
            parameters.put("contactsCertIssued", reqDTO.getContactsCertIssued());
            parameters.put("email", reqDTO.getEmail());
            //5:手持身份证合照
            HashMap<String, Object> handIdCard = new HashMap<>();
            handIdCard.put("img", PhotoUtil.transFerLinkToBase64(reqDTO.getHandIdCard()));
            handIdCard.put("imgSuffix", "jpg");
            handIdCard.put("imgType", "5");
            //7:营业执照
            HashMap<String, Object> businessLicense = new HashMap<>();
            businessLicense.put("img", PhotoUtil.transFerLinkToBase64(reqDTO.getBusinessLicense()));
            businessLicense.put("imgSuffix", "jpg");
            businessLicense.put("imgType", "7");
            //18:联系人身份证(头像)
            HashMap<String, Object> contactsIdCardFront = new HashMap<>();
            contactsIdCardFront.put("img", PhotoUtil.transFerLinkToBase64(reqDTO.getContactsIdCardFront()));
            contactsIdCardFront.put("imgSuffix", "jpg");
            contactsIdCardFront.put("imgType", "18");
            //19:联系人身份证(国徽)
            HashMap<String, Object> contactsIdCardBack = new HashMap<>();
            contactsIdCardBack.put("img", PhotoUtil.transFerLinkToBase64(reqDTO.getContactsIdCardBack()));
            contactsIdCardBack.put("imgSuffix", "jpg");
            contactsIdCardBack.put("imgType", "19");
            //20:法人身份证(头像)
            HashMap<String, Object> legalPersonIdCardFront = new HashMap<>();
            legalPersonIdCardFront.put("img", PhotoUtil.transFerLinkToBase64(reqDTO.getLegalPersonIdCardFront()));
            legalPersonIdCardFront.put("imgSuffix", "jpg");
            legalPersonIdCardFront.put("imgType", "20");
            //21:法人身份证(国徽)
            HashMap<String, Object> legalPersonIdCardBack = new HashMap<>();
            legalPersonIdCardBack.put("img", PhotoUtil.transFerLinkToBase64(reqDTO.getLegalPersonIdCardBack()));
            legalPersonIdCardBack.put("imgSuffix", "jpg");
            legalPersonIdCardBack.put("imgType", "21");
            //101:门头照图片
            HashMap<String, Object> doorPhoto = new HashMap<>();
            doorPhoto.put("img", PhotoUtil.transFerLinkToBase64(reqDTO.getLegalPersonIdCardBack()));
            doorPhoto.put("imgSuffix", "jpg");
            doorPhoto.put("imgType", "101");
            //102:场地照图片
            HashMap<String, Object> venuePhoto = new HashMap<>();
            venuePhoto.put("img", PhotoUtil.transFerLinkToBase64(reqDTO.getVenuePhoto()));
            venuePhoto.put("imgSuffix", "jpg");
            venuePhoto.put("imgType", "102");
            parameters.put("imgList", CollUtil.newArrayList(handIdCard, businessLicense
                    , contactsIdCardFront, contactsIdCardBack, legalPersonIdCardFront, legalPersonIdCardBack, doorPhoto, venuePhoto));
            CommonResult commonResult = sendPost(getPath(pathEnum.getPath()), parameters, aesKey);
            log.info("businessMerchantBaseInfoUpdate={}", JSONUtil.toJsonStr(commonResult));
        } catch (Exception e) {
            throw new BadRequestException(Convert.toStr(e.getMessage(), "企业/个体户商户基本信息修改失败"));
        }
        return Boolean.TRUE;
    }

    @Override
    public Boolean businessMerchantSettlementInfoUpdate(BusinessMerchantSettlementInfoUpdateReqDTO reqDTO) {
        BrandProductsLine brandProductsLine = queryBrandProductsLineByUser(SecurityUtils.getCurrentUserId(), CODE);
        String agentId = brandProductsLine.getAgentId();
        String aesKey = brandProductsLine.getAesKey();
        TokenTypeToPathEnum pathEnum = TokenTypeToPathEnum.findOne(TokenTypeToPathEnum.BUSINESS_MERCHANT_SETTLEMENT_INFO_UPDATE_PATH.getTokenType());
        String token = getToken(agentId, aesKey, pathEnum.getTokenType());

        ArrayList<HashMap<String, Object>> imgList = new ArrayList<>();
        try {
            SortedMap<String, Object> parameters = new TreeMap<>();
            parameters.put("agentId", agentId);
            parameters.put("token", token);
            parameters.put("merchId", reqDTO.getMerchId());
            parameters.put("gradeMerchLevel", reqDTO.getGradeMerchLevel());
            parameters.put("accountType", reqDTO.getAccountType());
            if (ObjectUtil.equal(reqDTO.getAccountType(), "G")) {
                //对公
                parameters.put("accountIdCommon", reqDTO.getAccountIdCommon());
                parameters.put("accountNameCommon", reqDTO.getAccountNameCommon());
                //11:银行开户许可证
                HashMap<String, Object> bankAccountOpeningLicense = new HashMap<>();
                bankAccountOpeningLicense.put("img", PhotoUtil.transFerLinkToBase64(reqDTO.getBankAccountOpeningLicense()));
                bankAccountOpeningLicense.put("imgSuffix", "jpg");
                bankAccountOpeningLicense.put("imgType", "11");
                imgList.add(bankAccountOpeningLicense);
            } else if (ObjectUtil.equal(reqDTO.getAccountType(), "S")) {
                //对私
                parameters.put("accountId", reqDTO.getAccountId());
                parameters.put("accountName", reqDTO.getAccountName());
                parameters.put("idCard", reqDTO.getIdCard());
                parameters.put("accountMobile", reqDTO.getAccountMobile());
                parameters.put("accountIdCardStartTime", reqDTO.getAccountIdCardStartTime());
                parameters.put("accountIdCardEndTime", reqDTO.getAccountIdCardEndTime());
                parameters.put("accountNation", reqDTO.getAccountNation());
                parameters.put("accountGender", reqDTO.getAccountGender());
                parameters.put("accountIdcardAddr", reqDTO.getAccountIdcardAddr());
                parameters.put("accountIdcardIssued", reqDTO.getAccountIdcardIssued());
                //3:对私结算身份证(国徽)
                HashMap<String, Object> privateIdCardBack = new HashMap<>();
                privateIdCardBack.put("img", PhotoUtil.transFerLinkToBase64(reqDTO.getBankAccountOpeningLicense()));
                privateIdCardBack.put("imgSuffix", "jpg");
                privateIdCardBack.put("imgType", "3");
                imgList.add(privateIdCardBack);
                //2:对私结算身份证(头像)
                HashMap<String, Object> privateIdCardFront = new HashMap<>();
                privateIdCardFront.put("img", PhotoUtil.transFerLinkToBase64(reqDTO.getBankAccountOpeningLicense()));
                privateIdCardFront.put("imgSuffix", "jpg");
                privateIdCardFront.put("imgType", "2");
                imgList.add(privateIdCardFront);
                //4:银行卡正面
                HashMap<String, Object> privateBankCardFront = new HashMap<>();
                privateBankCardFront.put("img", PhotoUtil.transFerLinkToBase64(reqDTO.getBankAccountOpeningLicense()));
                privateBankCardFront.put("imgSuffix", "jpg");
                privateBankCardFront.put("imgType", "4");
                imgList.add(privateBankCardFront);
            }
            parameters.put("typeCode", reqDTO.getTypeCode());
            parameters.put("typeName", reqDTO.getTypeName());
            parameters.put("bankCode", reqDTO.getBankCode());
            parameters.put("bankName", reqDTO.getBankName());
            parameters.put("bankProvince", reqDTO.getBankProvince());
            parameters.put("bankCity", reqDTO.getBankCity());
            parameters.put("imgList", imgList);
            CommonResult commonResult = sendPost(getPath(pathEnum.getPath()), parameters, aesKey);
            log.info("businessMerchantSettlementInfoUpdate={}", JSONUtil.toJsonStr(commonResult));
        } catch (Exception e) {
            throw new BadRequestException(Convert.toStr(e.getMessage(), "企业/个体户商户结算信息修改失败"));
        }
        return Boolean.TRUE;
    }

    @Override
    public Boolean businessMerchantNetworkAccess(BusinessMerchantNetworkAccessReqDTO reqDTO) {
        BrandProductsLine brandProductsLine = queryBrandProductsLineByUser(SecurityUtils.getCurrentUserId(), CODE);
        String agentId = brandProductsLine.getAgentId();
        String aesKey = brandProductsLine.getAesKey();
        ArrayList<ImageInfoRspDTO> imgList = new ArrayList<>();
        TokenTypeToPathEnum pathEnum = TokenTypeToPathEnum.findOne(TokenTypeToPathEnum.BUSINESS_MERCHANT_NET_WORK_ACCESS_PATH.getTokenType());
        String token = getToken(agentId, aesKey, pathEnum.getTokenType());
        try {
            SortedMap<String, Object> parameters = new TreeMap<>();
            parameters.put("agentId", agentId);
            parameters.put("token", token);
            parameters.put("reqFlowNo", "");
            parameters.put("merchLevel", reqDTO.getMerchLevel());
            parameters.put("merchName", reqDTO.getMerchName());
            parameters.put("merchPname", reqDTO.getMerchPname());
            parameters.put("licenseNo", reqDTO.getLicenseNo());
            parameters.put("licensePapersType", reqDTO.getLicensePapersType());
            parameters.put("licenseIssuedAuth", reqDTO.getLicenseIssuedAuth());
            parameters.put("licenseStartTime", reqDTO.getLicenseStartTime());
            parameters.put("licenseEndTime", reqDTO.getLicenseEndTime());
            parameters.put("registerCapital", reqDTO.getRegisterCapital());
            parameters.put("licenseAddr", reqDTO.getLicenseAddr());
            parameters.put("busiScope", reqDTO.getBusiScope());
            parameters.put("mcc", reqDTO.getMcc());
            parameters.put("mccIdPath", reqDTO.getMccIdPath());
            parameters.put("mccNamePath", reqDTO.getMccNamePath());
            parameters.put("regionIdPath", reqDTO.getRegionIdPath());
            parameters.put("regionNamePath", reqDTO.getRegionNamePath());
            parameters.put("busiAddr", reqDTO.getBusiAddr());
            parameters.put("legalMobile", reqDTO.getLegalMobile());
            parameters.put("legalName", reqDTO.getLegalName());
            parameters.put("legalCertNo", reqDTO.getLegalCertNo());
            parameters.put("legalNation", reqDTO.getLegalNation());
            parameters.put("legalGender", reqDTO.getLegalGender());
            parameters.put("legalIssuedBy", reqDTO.getLegalIssuedBy());
            parameters.put("legalAddr", reqDTO.getLegalAddr());
            parameters.put("legalCertDateStart", reqDTO.getLegalCertDateStart());
            parameters.put("legalCertDateEnd", reqDTO.getLegalCertDateEnd());
            parameters.put("contactsMobile", reqDTO.getContactsMobile());
            parameters.put("contactsEmail", reqDTO.getContactsEmail());
            parameters.put("contactsName", reqDTO.getContactsName());
            parameters.put("contactsCertNo", reqDTO.getContactsCertNo());
            parameters.put("contactsNation", reqDTO.getContactsNation());
            parameters.put("contactsGender", reqDTO.getContactsGender());
            parameters.put("contactsIssuedBy", reqDTO.getContactsIssuedBy());
            parameters.put("contactsAddr", reqDTO.getContactsAddr());
            parameters.put("contactsCertDateStart", reqDTO.getLegalCertDateStart());
            parameters.put("contactsCertDateEnd", reqDTO.getContactsCertDateEnd());
            parameters.put("accountSettType", reqDTO.getAccountSettType());
            if (ObjectUtil.equal(reqDTO.getAccountSettType(), "G")) {
                //对公
                parameters.put("accountCorporateName", reqDTO.getAccountCorporateName());
                parameters.put("accountCorporateCardNo", reqDTO.getAccountCorporateCardNo());
                ImageInfoRspDTO bankAccountOpeningLicense = ImageInfoRspDTO.builder()
                        .img(PhotoUtil.transFerLinkToBase64(reqDTO.getBankAccountOpeningLicense()))
                        .imgType("jpg")
                        .mgSuffix("11").build();
                imgList.add(bankAccountOpeningLicense);
            } else if (ObjectUtil.equal(reqDTO.getAccountSettType(), "S")) {
                //对私
                parameters.put("accountPrivateCardNo", reqDTO.getAccountPrivateCardNo());
                parameters.put("accountPrivateName", reqDTO.getAccountPrivateName());
                parameters.put("accountPrivateMobile", reqDTO.getAccountPrivateMobile());
                parameters.put("accountPrivateCertNo", reqDTO.getAccountPrivateCertNo());
                parameters.put("accountPrivateNation", reqDTO.getAccountPrivateNation());
                parameters.put("accountPrivateGender", reqDTO.getAccountPrivateGender());
                parameters.put("accountPrivateIssuedBy", reqDTO.getAccountPrivateIssuedBy());
                parameters.put("accountPrivateAddr", reqDTO.getAccountPrivateAddr());
                parameters.put("accountPrivateCertDateStart", reqDTO.getAccountPrivateCertDateStart());
                parameters.put("accountPrivateCertDateEnd", reqDTO.getAccountPrivateCertDateEnd());
                //对私结算身份证(头像)
                ImageInfoRspDTO PrivateIdCardFront = ImageInfoRspDTO.builder()
                        .img(PhotoUtil.transFerLinkToBase64(reqDTO.getPrivateIdCardFront()))
                        .imgType("jpg")
                        .mgSuffix("2").build();
                //对私结算身份证(国徽)
                ImageInfoRspDTO PrivateIdCardBack = ImageInfoRspDTO.builder()
                        .img(PhotoUtil.transFerLinkToBase64(reqDTO.getPrivateIdCardBack()))
                        .imgType("jpg")
                        .mgSuffix("3").build();
                //银行卡正面
                ImageInfoRspDTO privateBankCardFront = ImageInfoRspDTO.builder()
                        .img(PhotoUtil.transFerLinkToBase64(reqDTO.getPrivateBankCardFront()))
                        .imgType("jpg")
                        .mgSuffix("4").build();
                imgList.add(PrivateIdCardFront);
                imgList.add(PrivateIdCardBack);
                imgList.add(privateBankCardFront);
            }
            parameters.put("accountBankNo", reqDTO.getAccountBankNo());
            parameters.put("accountBankName", reqDTO.getAccountBankName());
            parameters.put("cFeeRate", reqDTO.getCFeeRate());
            parameters.put("dFeeRate", reqDTO.getDFeeRate());
            parameters.put("dFeeMax", reqDTO.getDFeeMax());
            parameters.put("wechatPayFeeRate", reqDTO.getWechatPayFeeRate());
            parameters.put("alipayFeeRate", reqDTO.getAlipayFeeRate());
            parameters.put("ycFreeFeeRate", reqDTO.getYcFreeFeeRate());
            parameters.put("ydFreeFeeRate", reqDTO.getYdFreeFeeRate());
            parameters.put("d0FeeRate", reqDTO.getDlFeeRate());
            parameters.put("d0SingleCashDrawal", reqDTO.getDlSingleCashDrawal());
            parameters.put("termSn", reqDTO.getTermSn());
            //营业执照照片
            ImageInfoRspDTO businessLicense = ImageInfoRspDTO.builder()
                    .img(PhotoUtil.transFerLinkToBase64(reqDTO.getBusinessLicense()))
                    .imgType("jpg")
                    .mgSuffix("7").build();
            //联系人身份证(头像)
            ImageInfoRspDTO contactsIdCardFront = ImageInfoRspDTO.builder()
                    .img(PhotoUtil.transFerLinkToBase64(reqDTO.getContactsIdCardFront()))
                    .imgType("jpg")
                    .mgSuffix("18").build();
            //联系人身份证(国徽)
            ImageInfoRspDTO contactsIdCardBack = ImageInfoRspDTO.builder()
                    .img(PhotoUtil.transFerLinkToBase64(reqDTO.getContactsIdCardBack()))
                    .imgType("jpg")
                    .mgSuffix("19").build();
            //法人身份证(头像)
            ImageInfoRspDTO legalPersonIdCardFront = ImageInfoRspDTO.builder()
                    .img(PhotoUtil.transFerLinkToBase64(reqDTO.getLegalPersonIdCardFront()))
                    .imgType("jpg")
                    .mgSuffix("20").build();
            //法人身份证(国徽)
            ImageInfoRspDTO legalPersonIdCardBack = ImageInfoRspDTO.builder()
                    .img(PhotoUtil.transFerLinkToBase64(reqDTO.getLegalPersonIdCardBack()))
                    .imgType("jpg")
                    .mgSuffix("21").build();
            //门头照片
            ImageInfoRspDTO doorPhoto = ImageInfoRspDTO.builder()
                    .img(PhotoUtil.transFerLinkToBase64(reqDTO.getDoorPhoto()))
                    .imgType("jpg")
                    .mgSuffix("101").build();
            //场地照图片
            ImageInfoRspDTO venuePhoto = ImageInfoRspDTO.builder()
                    .img(PhotoUtil.transFerLinkToBase64(reqDTO.getVenuePhoto()))
                    .imgType("jpg")
                    .mgSuffix("102").build();
            //5:手持身份证合照
            ImageInfoRspDTO handIdCard = ImageInfoRspDTO.builder()
                    .img(PhotoUtil.transFerLinkToBase64(reqDTO.getHandIdCard()))
                    .imgType("jpg")
                    .mgSuffix("5").build();
            imgList.add(businessLicense);
            imgList.add(contactsIdCardFront);
            imgList.add(contactsIdCardBack);
            imgList.add(legalPersonIdCardFront);
            imgList.add(legalPersonIdCardBack);
            imgList.add(doorPhoto);
            imgList.add(venuePhoto);
            imgList.add(handIdCard);
            parameters.put("imgList", imgList);
            CommonResult commonResult = sendPost(getPath(pathEnum.getPath()), parameters, aesKey);
            log.info("businessMerchantNetworkAccess={}", JSONUtil.toJsonStr(commonResult));
        } catch (Exception e) {
            throw new BadRequestException(Convert.toStr(e.getMessage(), "企业/个体户商户入网失败"));
        }
        return Boolean.TRUE;
    }

    @Override
    public MerchantMergeWithdrawalQueryRspDTO merchantMergeWithdrawalQuery(MerchantMergeWithdrawalQueryReqDTO reqDTO) {
        BrandProductsLine brandProductsLine = queryBrandProductsLineByUser(SecurityUtils.getCurrentUserId(), CODE);
        String agentId = brandProductsLine.getAgentId();
        String aesKey = brandProductsLine.getAesKey();
        TokenTypeToPathEnum pathEnum = TokenTypeToPathEnum.findOne(TokenTypeToPathEnum.MERCHANT_MERGE_WITHDRAWAL_QUERY_PATH.getTokenType());
        String token = getToken(agentId, aesKey, pathEnum.getTokenType());
        SortedMap<String, Object> parameters = new TreeMap<>();
        parameters.put("agentId", agentId);
        parameters.put("token", token);
        parameters.put("merchId", reqDTO.getMerchId());
        CommonResult commonResult = sendPost(getPath(pathEnum.getPath()), parameters, aesKey);
        log.info("merchantMergeWithdrawalQuery={}", JSONUtil.toJsonStr(commonResult));
        return JSONUtil.toBean(commonResult.getData(), MerchantMergeWithdrawalQueryRspDTO.class);
    }

    @Override
    public MerchantMergeWithdrawalUpdateRspDTO merchantMergeWithdrawalUpdate(MerchantMergeWithdrawalUpdateReqDTO reqDTO) {
        BrandProductsLine brandProductsLine = queryBrandProductsLineByUser(SecurityUtils.getCurrentUserId(), CODE);
        String agentId = brandProductsLine.getAgentId();
        String aesKey = brandProductsLine.getAesKey();
        TokenTypeToPathEnum pathEnum = TokenTypeToPathEnum.findOne(TokenTypeToPathEnum.MERCHANT_MERGE_WITHDRAWAL_UPDATE_PATH.getTokenType());
        String token = getToken(agentId, aesKey, pathEnum.getTokenType());
        SortedMap<String, Object> parameters = new TreeMap<>();
        parameters.put("agentId", agentId);
        parameters.put("token", token);
        parameters.put("merchId", reqDTO.getMerchId());
        parameters.put("mergeFlag", reqDTO.getMergeFlag());
        CommonResult commonResult = sendPost(getPath(pathEnum.getPath()), parameters, aesKey);
        log.info("merchantMergeWithdrawalUpdate={}", JSONUtil.toJsonStr(commonResult));
        return JSONUtil.toBean(commonResult.getData(), MerchantMergeWithdrawalUpdateRspDTO.class);
    }

    @Override
    public MerchantWalletQueryRspDTO merchantWalletQuery(MerchantWalletQueryReqDTO reqDTO) {
        BrandProductsLine brandProductsLine = queryBrandProductsLineByUser(SecurityUtils.getCurrentUserId(), CODE);
        String agentId = brandProductsLine.getAgentId();
        String aesKey = brandProductsLine.getAesKey();
        TokenTypeToPathEnum pathEnum = TokenTypeToPathEnum.findOne(TokenTypeToPathEnum.MERCHANT_WALLET_QUERY_PATH.getTokenType());
        String token = getToken(agentId, aesKey, pathEnum.getTokenType());
        SortedMap<String, Object> parameters = new TreeMap<>();
        parameters.put("agentId", agentId);
        parameters.put("token", token);
        parameters.put("merchId", reqDTO.getMerchId());
        CommonResult commonResult = sendPost(getPath(pathEnum.getPath()), parameters, aesKey);
        log.info("merchantWalletQuery={}", JSONUtil.toJsonStr(commonResult));
        return JSONUtil.toBean(commonResult.getData(), MerchantWalletQueryRspDTO.class);
    }

    @Override
    public MerchantWithdrawalsListQueryRspDTO merchantWithdrawalsListQuery(MerchantWalletQueryReqDTO reqDTO) {
        BrandProductsLine brandProductsLine = queryBrandProductsLineByUser(SecurityUtils.getCurrentUserId(), CODE);
        String agentId = brandProductsLine.getAgentId();
        String aesKey = brandProductsLine.getAesKey();
        TokenTypeToPathEnum pathEnum = TokenTypeToPathEnum.findOne(TokenTypeToPathEnum.MERCHANT_WITHDRAWALS_LIST_QUERY_PATH.getTokenType());
        String token = getToken(agentId, aesKey, pathEnum.getTokenType());
        SortedMap<String, Object> parameters = new TreeMap<>();
        parameters.put("agentId", agentId);
        parameters.put("token", token);
        parameters.put("merchId", reqDTO.getMerchId());
        CommonResult commonResult = sendPost(getPath(pathEnum.getPath()), parameters, aesKey);
        log.info("merchantWithdrawalsListQuery={}", JSONUtil.toJsonStr(commonResult));
        return JSONUtil.toBean(commonResult.getData(), MerchantWithdrawalsListQueryRspDTO.class);
    }

    @Override
    public Boolean merchantMergerWithdrawalApplication(MerchantMergerWithdrawalApplicationReqDTO reqDTO) {
        BrandProductsLine brandProductsLine = queryBrandProductsLineByUser(SecurityUtils.getCurrentUserId(), CODE);
        TokenTypeToPathEnum pathEnum = TokenTypeToPathEnum.findOne(TokenTypeToPathEnum.MERCHANT_MERGER_WITHDRAWAL_APPLICATION_PATH.getTokenType());
        String agentId = brandProductsLine.getAgentId();
        String aesKey = brandProductsLine.getAesKey();
        String token = getToken(agentId, aesKey, pathEnum.getTokenType());
        try {
            SortedMap<String, Object> parameters = new TreeMap<>();
            parameters.put("agentId", agentId);
            parameters.put("token", token);
            parameters.put("merchId", reqDTO.getMerchId());
            parameters.put("outReqFlowNo", NoUtil.getOrderNo(32));
            parameters.put("withdrawAmt", reqDTO.getWithdrawAmt());
            parameters.put("withdrawId", reqDTO.getWithdrawId());
            CommonResult commonResult = sendPost(getPath(pathEnum.getPath()), parameters, aesKey);
            log.info("merchantMergerWithdrawalApplication={}", JSONUtil.toJsonStr(commonResult));
        } catch (Exception e) {
            throw new BadRequestException(Convert.toStr(e.getMessage(), "商户待提现列表查询失败"));
        }
        return Boolean.TRUE;
    }

    @Override
    public MerchantWithdrawalQueryRspDTO merchantWithdrawalQuery(MerchantWithdrawalQueryReqDTO reqDTO) {
        BrandProductsLine brandProductsLine = queryBrandProductsLineByUser(SecurityUtils.getCurrentUserId(), CODE);
        TokenTypeToPathEnum pathEnum = TokenTypeToPathEnum.findOne(TokenTypeToPathEnum.MERCHANT_WITHDRAWAL_QUERY_PATH.getTokenType());
        String agentId = brandProductsLine.getAgentId();
        String aesKey = brandProductsLine.getAesKey();
        String token = getToken(agentId, aesKey, pathEnum.getTokenType());

        SortedMap<String, Object> parameters = new TreeMap<>();
        parameters.put("agentId", agentId);
        parameters.put("token", token);
        parameters.put("merchId", reqDTO.getMerchId());
        parameters.put("outReqFlowNo", reqDTO.getOutReqFlowNo());
        CommonResult commonResult = sendPost(getPath(pathEnum.getPath()), parameters, aesKey);
        log.info("merchantWithdrawalQuery={}", JSONUtil.toJsonStr(commonResult));
        return JSONUtil.toBean(commonResult.getData(), MerchantWithdrawalQueryRspDTO.class);
    }


    @Override
    public List<CityRspDTO> queryArea(QueryProvinceReqDTO queryProvinceReqDTO) {
        BrandProductsLine brandProductsLine = queryBrandProductsLineByUser(SecurityUtils.getCurrentUserId(), CODE);
        String agentId = brandProductsLine.getAgentId();
        String aesKey = brandProductsLine.getAesKey();
        TokenTypeToPathEnum pathEnum = TokenTypeToPathEnum.findOne(TokenTypeToPathEnum.QUERY_PROVINCE_PATH.getTokenType());
        String token = getToken(agentId, aesKey, pathEnum.getTokenType());
        SortedMap<String, Object> parameters = new TreeMap<>();
        parameters.put("agentId", agentId);
        parameters.put("token", token);
        CommonResult commonResult = sendPost(getPath(pathEnum.getPath()), parameters, aesKey);
        log.info("queryProvince={}", JSONUtil.toJsonStr(commonResult));
        return JSONUtil.toList(commonResult.getData(), CityRspDTO.class);
    }

    @Override
    public List<CityRspDTO> queryCity(QueryCityReqDTO queryCityReqDTO) {
        BrandProductsLine brandProductsLine = queryBrandProductsLineByUser(SecurityUtils.getCurrentUserId(), CODE);
        String agentId = brandProductsLine.getAgentId();
        String aesKey = brandProductsLine.getAesKey();
        TokenTypeToPathEnum pathEnum = TokenTypeToPathEnum.findOne(TokenTypeToPathEnum.QUERY_CITY_PATH.getTokenType());
        String token = getToken(agentId, aesKey, pathEnum.getTokenType());
        SortedMap<String, Object> parameters = new TreeMap<>();
        parameters.put("agentId", agentId);
        parameters.put("token", token);
        parameters.put("provinceCode", queryCityReqDTO.getProvinceCode());
        CommonResult commonResult = sendPost(getPath(pathEnum.getPath()), parameters, aesKey);
        log.info("queryCity={}", JSONUtil.toJsonStr(commonResult));
        return JSONUtil.toList(commonResult.getData(), CityRspDTO.class);
    }

    @Override
    public List<CityRspDTO> queryCounty(QueryCountyReqDTO queryCountyReqDTO) {
        BrandProductsLine brandProductsLine = queryBrandProductsLineByUser(SecurityUtils.getCurrentUserId(), CODE);
        String agentId = brandProductsLine.getAgentId();
        String aesKey = brandProductsLine.getAesKey();
        TokenTypeToPathEnum pathEnum = TokenTypeToPathEnum.findOne(TokenTypeToPathEnum.QUERY_COUNTY_PATH.getTokenType());
        String token = getToken(agentId, aesKey, pathEnum.getTokenType());
        SortedMap<String, Object> parameters = new TreeMap<>();
        parameters.put("agentId", agentId);
        parameters.put("token", token);
        parameters.put("cityCode", queryCountyReqDTO.getCityCode());
        CommonResult commonResult = sendPost(getPath(pathEnum.getPath()), parameters, aesKey);
        log.info("queryCounty={}", JSONUtil.toJsonStr(commonResult));
        return JSONUtil.toList(commonResult.getData(), CityRspDTO.class);
    }

    @Override
    public List<BankRspDTO> queryBank(QueryBankCardReqDTO queryCountyReqDTO) {
        BrandProductsLine brandProductsLine = queryBrandProductsLineByUser(SecurityUtils.getCurrentUserId(), CODE);
        String agentId = brandProductsLine.getAgentId();
        String aesKey = brandProductsLine.getAesKey();
        TokenTypeToPathEnum pathEnum = TokenTypeToPathEnum.findOne(TokenTypeToPathEnum.QUERY_BANK_PATH.getTokenType());
        String token = getToken(agentId, aesKey, pathEnum.getTokenType());
        SortedMap<String, Object> parameters = new TreeMap<>();
        parameters.put("agentId", agentId);
        parameters.put("token", token);
        parameters.put("provinceCode", queryCountyReqDTO.getProvinceCode());
        parameters.put("cityCode", queryCountyReqDTO.getCityCode());
        parameters.put("bankNameKeyword", queryCountyReqDTO.getBankNameKeyword());
        CommonResult commonResult = sendPost(getPath(pathEnum.getPath()), parameters, aesKey);
        log.info("queryBank={}", JSONUtil.toJsonStr(commonResult));
        return JSONUtil.toList(commonResult.getData(), BankRspDTO.class);
    }


    public String getPath(String path) {
        return TokenTypeToPathEnum.BASE_PATH.getPath() + path;
    }

    public String getToken(String agentId, String aesKey, String tokenType) {
        SortedMap<String, Object> parameters = new TreeMap<>();
        parameters.put("agentId", agentId);
        parameters.put("tokenType", tokenType);
        CommonResult commonResult = sendPost(getPath(TokenTypeToPathEnum.TOKEN_PATH.getPath()), parameters, aesKey);
        String data = commonResult.getData();
        Map map = JSONUtil.parse(data).toBean(Map.class);
        return Convert.toStr(map.get("token"));
    }


    public CommonResult sendPost(String path, SortedMap<String, Object> parameters, String aesKey) {
        String sign = DESUtil.signByMap(parameters, aesKey);
        parameters.put("sign", sign);
        String post = HttpUtil.post(path, JSONUtil.toJsonStr(parameters));
        CommonResult commonResult = JSONUtil.toBean(post, CommonResult.class);
        if (ObjectUtil.notEqual(commonResult.getCode(), "00")) {
            throw new BadRequestException(commonResult.getMessage());
        }
        return commonResult;
    }

    public BrandProductsLine queryBrandProductsLineByUser(Long userId, String channelCode) {
        User user = userService.lambdaQuery().eq(User::getId, userId).one();
        ProductsLine productsLine = productsLineService.lambdaQuery()
                .eq(ProductsLine::getCode, ChannelEnum.ZF.getCode()).one();
        BrandProductsLine brandProductsLine = brandProductsLineService.lambdaQuery()
                .eq(BrandProductsLine::getProductLineId, productsLine.getId()).one();
//                .eq(BrandProductsLine::getUserId, user.getOneId()).one();
        if (ObjectUtil.isNull(brandProductsLine)) {
            throw new BadRequestException("该产品线未授权");
        }
        return brandProductsLine;
    }


}
